package com.nx.platform.es.bean.modle.query;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import com.nx.platform.es.bean.dto.RequestContext;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.common.Strings;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

/**
 * @author
 * @since 2016年10月15日
 */
public class BooleanHandler implements QueryFieldHandler {

    @Override
    public void handle(ImmutableMap<String, ?> fieldConfig, RequestContext context, String fieldFace,
                       StatementOperator operator, String fieldValue, ListMultimap<Boolean, QueryBuilder> queryBuilders) {
        if (Strings.isNullOrEmpty(fieldValue)) {
            fieldValue = MapUtils.getString(fieldConfig, "default");
        }
        if (Strings.isNullOrEmpty(fieldValue)) {
            return;
        }
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        Preconditions.checkState(!Strings.isNullOrEmpty(fieldName));
        if ("0".equals(fieldValue) || "false".equalsIgnoreCase(fieldValue)) {
            // 记录Query信息(Trace)
            context.getTrace().append("&").append(fieldFace).append(operator.getSymbol()).append(fieldValue);
            //
            queryBuilders.put(operator.isSign(), QueryBuilders.termQuery(fieldName, false));
        } else if ("1".equals(fieldValue) || "true".equalsIgnoreCase(fieldValue)) {
            // 记录Query信息(Trace)
            context.getTrace().append("&").append(fieldFace).append(operator.getSymbol()).append(fieldValue);
            //
            queryBuilders.put(operator.isSign(), QueryBuilders.termQuery(fieldName, true));
        }
    }

}
